package com.great.controller;

import com.github.pagehelper.PageInfo;
import com.great.dao.IndexDao;
import com.great.dao.ProductDao;
import com.great.domain.*;
import com.great.service.CateService;
import com.great.service.IndexService;
import com.great.service.ProductService;
import com.great.utils.VerificationCode;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

@Controller
@RequestMapping("/index")
public class IndexController {

    @Autowired
    private IndexService indexService;

    @Autowired
    private IndexDao indexDao;

    @Autowired
    private ProductDao productDao;

    @Autowired
    private CateService cateService;

    @Autowired
    private ProductService productService;

    @GetMapping("/verifyCode")
    public void verifyCode(HttpServletRequest request, HttpServletResponse resp) throws IOException {
        VerificationCode code = new VerificationCode();
        BufferedImage image = code.getImage();
        String text = code.getText();
        HttpSession session = request.getSession(true);
        session.setAttribute("verify_code", text);
        VerificationCode.output(image,resp.getOutputStream());
    }

    @RequestMapping("/base")
    public ModelAndView searchtitle(){
        ModelAndView mv = new ModelAndView("index");
        List<Cate> flist = indexService.findAllParentCate();
        mv.addObject("flist",flist);
        List<Cate> clist = indexService.findAllChildCate();
        mv.addObject("clist",clist);
        List<Product> fz = indexService.findAllfproduct(3);
        List<Product> dz = indexService.findAllfproduct(1);
        List<Product> mz = indexService.findAllfproduct(6);
        mv.addObject("fz",fz);
        mv.addObject("dz",dz);
        mv.addObject("mz",mz);
        return mv;
    }
    @RequestMapping("/mydata")
    public ModelAndView mydata(){
        ModelAndView mv = new ModelAndView("Mydata");
        List<Cate> flist = indexService.findAllParentCate();
        mv.addObject("flist",flist);
        List<Cate> clist = indexService.findAllChildCate();
        mv.addObject("clist",clist);
        return mv;
    }
    @RequestMapping("/changedata")
    public ModelAndView changedata(){
        ModelAndView mv = new ModelAndView("changedata");
        List<Cate> flist = indexService.findAllParentCate();
        mv.addObject("flist",flist);
        List<Cate> clist = indexService.findAllChildCate();
        mv.addObject("clist",clist);
        return mv;
    }

    @RequestMapping("/selectproduct")
    public ModelAndView selectproduct(Integer fid, Integer cid, @RequestParam(name = "page", required = true,defaultValue = "1") int page, @RequestParam(name = "size",required = true,defaultValue = "20") int size){
        ModelAndView mv = new ModelAndView("productlist");
        List<Cate> flist = indexService.findAllParentCate();
        mv.addObject("flist",flist);
        List<Cate> clist = indexService.findAllChildCate();
        mv.addObject("clist",clist);

        if(cid==null){
            Cate cate = cateService.findById(fid);
            mv.addObject("cate",cate);
            List<Product> product = indexService.findAllfproduct(fid);
            mv.addObject("product",product);
        }
        if(cid!=null){
            Cate cate = cateService.findById(cid);
            Cate catef = cateService.findById(cate.getCate_parent_id());
            List<Product> product = indexService.findAllcproduct(cid);
            mv.addObject("product",product);
            mv.addObject("cate",cate);
            mv.addObject("catef",catef);
        }
        return mv;
    }

    @RequestMapping("/productdetails")
    public ModelAndView productdetails(Integer product_id){
        ModelAndView mv = new ModelAndView("prodetails");
        List<Cate> flist = indexService.findAllParentCate();
        mv.addObject("flist",flist);
        List<Cate> clist = indexService.findAllChildCate();
        mv.addObject("clist",clist);
        Product product = productService.findproductById(product_id);
        mv.addObject("product",product);
        return mv;
    }

    @RequestMapping("/productoperation")
    public void productoperation(Integer product_id, Integer cart_num, HttpSession session,HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        User user = (User)session.getAttribute("user");
        if(user!=null){
            String user_id = user.getId();
            Integer count = indexService.checkcart(user_id,product_id);
            //若购物车不存在该商品，则添加到购物车
            if(count==0) {
                Product product = productService.findproductById(product_id);
                indexService.addcart(user_id, product_id, cart_num);
                out.println("<script>");
                out.println("alert('添加到购物车成功');");
                out.println("history.back();");
                out.println("</script>");
                out.close();
            }
            //若购物车存在已存在该商品,则更新商品的数量
            else {
                int newcount = count+cart_num;
                indexService.updatecart_num(user_id,product_id,newcount);
                out.println("<script>");
                out.println("alert('添加到购物车成功');");
                out.println("history.back();");
                out.println("</script>");
                out.close();
            }
        }else{
            out.println("<script>");
            out.println("alert('请登陆后再进行操作');");
            out.println("history.back();");
            out.println("</script>");
            out.close();
        }
    }

    @RequestMapping("/findcart")
    public ModelAndView findcart(HttpSession session){
        ModelAndView mv = new ModelAndView("cart");
        List<Cate> flist = indexService.findAllParentCate();
        mv.addObject("flist",flist);
        List<Cate> clist = indexService.findAllChildCate();
        mv.addObject("clist",clist);
        User user = (User)session.getAttribute("user");
        String id = user.getId();
        List<Cart> cart = indexService.findcart(id);
        mv.addObject("cart",cart);
        return mv;
    }

    @RequestMapping("/cart_numchange")
    public void cart_numchange(Integer count,Integer cart_id){
        indexService.cart_numchange(cart_id,count);
    }

    @RequestMapping("/cart_del")
    public void cart_del(Integer cart_id){
        indexService.cart_del(cart_id);
    }

    @RequestMapping("/manydelete")
    public void manydelete(String str) {
        String[] id = str.split(",");
        for(int i=0;i<id.length;i++){
            indexService.cart_del(Integer.parseInt(id[i]));
        }
    }

    @RequestMapping("/order")
    public ModelAndView order(@RequestParam("str") String str){
        ModelAndView mv = new ModelAndView("order");
        double totalprice = 0;
        int count = 0;
        String[] id = str.split(",");
        List<Cart> carts = new ArrayList<>();
        List<Cate> flist = indexService.findAllParentCate();
        mv.addObject("flist",flist);
        List<Cate> clist = indexService.findAllChildCate();
        mv.addObject("clist",clist);
        for(int i=0;i<id.length;i++){
            Cart es = indexService.searchcartrecord(Integer.parseInt(id[i]));
            double dprice = es.getProduct().getProduct_price()* es.getCart_num();
            totalprice +=dprice;
            int num = es.getCart_num();
            count += num;
            carts.add(es);
        }
        mv.addObject("count",count);
        mv.addObject("totalprice",totalprice);
        mv.addObject("order",carts);
        return mv;
    }
    @RequestMapping("/addorder")
    public String makeorder( String str,
                             String address,
                             String phone,
                             String realname,
                            HttpSession session){
        String[] id = str.split(",");
        User user = (User)session.getAttribute("user");
        String user_id = user.getId();
        for (int i=0;i< id.length;i++){
            //获取当前时间
            SimpleDateFormat sdfTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //获取订单创建时间
            Date createTime = new Date();
            String lastime = sdfTime.format(new Date()).replaceAll("[[\\s-:punct:]]", "");

            Cart es = indexService.searchcartrecord(Integer.parseInt(id[i]));
            Order order = new Order();

            order.setCreate_time(createTime);
            order.setUser_id(user_id);
            order.setProduct_id(es.getProduct_id());
            order.setPrice(es.getProduct().getProduct_price()* es.getCart_num());
            order.setNum(es.getCart_num());

            int kucun=es.getProduct().getProduct_stock()-es.getCart_num();


            order.setAddress(address);
            order.setPhone(phone);
            order.setRealname(realname);


            indexService.addorder(order);
            productDao.updateproduct(es.getProduct_id(),kucun);
            indexService.cart_del(Integer.parseInt(id[i]));
        }
        return "redirect:/index/myorder";
    }

    @RequestMapping("/myorder")
    public ModelAndView myorder(HttpSession session,@RequestParam(name = "page", required = true,defaultValue = "1") int page, @RequestParam(name = "size",required = true,defaultValue = "5") int size){
        ModelAndView mv = new ModelAndView("myorder");
        List<Cate> flist = indexService.findAllParentCate();
        mv.addObject("flist",flist);
        List<Cate> clist = indexService.findAllChildCate();
        mv.addObject("clist",clist);
        User user = (User) session.getAttribute("user");
        List<Order> orders = indexService.getorder(user.getId(),page,size);
        PageInfo pageInfo = new PageInfo(orders);
        mv.addObject("pageInfo",pageInfo);
        mv.addObject("orders",orders);
        return mv;
    }
    //退货
    @RequestMapping("/updatestatus")
    public String changeGood(String order_id,int product_id,int order_num, HttpSession session){
        Product product = productService.findproductById(product_id);
        int kuncun= product.getProduct_stock()+order_num;
        productDao.updateproduct(product_id,kuncun);
        indexDao.updateorderstatus(order_id);
        return "redirect:/index/myorder";
    }



    //确认收货
    @RequestMapping("/comfim")
    public String comfim(String order_id){
        indexDao.comfim(order_id);
        return "redirect:/index/myorder";
    }

}
